import 'package:audioplayers/audioplayers.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sabre_sync_fencing/dd_core/dd_other.dart';

import '../../../dd_core/dd_log_service.dart';
import '../../../dd_models/dd_hive_comment_model.dart';
import '../../../dd_models/dd_hive_works_model.dart';
import '../../../r.dart';
import '../../dd_personal_center/views/dd_view_background.dart';
import '../controllers/dd_comment_controller.dart';
import '../views/dd_sounds/dd_sounds_button/sounds_button.dart';
import '../views/dd_sounds/dd_utils/recorder.dart';

class DDCommentPage extends StatelessWidget {
  final HiveWorksModel model;

  final DDCommentController commentController;

  final bool? onlyText;

  const DDCommentPage({
    super.key,
    required this.model,
    required this.commentController,
    this.onlyText = false,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DDCommentController>(
      init: commentController,
      initState: (state) {
        commentController.setModel(model);
        commentController.getList(model);
        DDLogService().ddGa(page: "commen");
      },
      builder: (controller) {
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets,
          duration: const Duration(milliseconds: 100),
          curve: Curves.decelerate,
          child: DraggableScrollableSheet(
            initialChildSize: 0.6,
            minChildSize: 0.5,
            maxChildSize: 0.6,
            expand: false,
            builder: (context, scrollController) {
              return GestureDetector(
                onTap: () {
                  FocusScope.of(context).unfocus();
                },
                child: Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius:
                        BorderRadius.vertical(top: Radius.circular(20)),
                    border: Border(
                      top: BorderSide(color: Color(0xFF4C5961), width: 2),
                      left: BorderSide.none,
                      right: BorderSide.none,
                      bottom: BorderSide.none,
                    ),
                  ),
                  child: SafeArea(
                    child: SingleChildScrollView(
                      child: Obx(
                        () => Column(
                          children: [
                            Container(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(height: 10),
                                  Text(
                                    "Comment",
                                    style: TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              height: MediaQuery.of(context).size.height * 0.42,
                              child: ListView.builder(
                                // reverse: true,
                                shrinkWrap: false,
                                controller: controller.scrollController,
                                itemBuilder: (context, index) {
                                  return CommentItem(
                                      model: controller.messageList[index],
                                      onClick: () {
                                        DDLogService().ddGa(page: "commen_like");
                                        controller.updateMyLike(
                                            controller.messageList[index]);
                                      });
                                },
                                itemCount: controller.messageList.length,
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 10, top: 10),
                              decoration: const BoxDecoration(
                                color: Colors.white,
                                border: Border(
                                  top: BorderSide(
                                      color: Color(0xFF53BFD7), width: 1),
                                ),
                              ),
                              child: Row(
                                children: [
                                  IconButton(
                                      onPressed: this.onlyText == true
                                          ? null
                                          : () {
                                              controller.speakState.value =
                                                  !controller.speakState.value;
                                            },
                                      icon: this.onlyText == true
                                          ? Image.asset(
                                              R.assetsImagesHome9,
                                              color: Colors.transparent,
                                            )
                                          : (controller.speakState.value
                                              ? Image.asset(R.assetsImagesHome9)
                                              : Image.asset(
                                                  R.assetsImagesHome14))),
                                  SizedBox(width: 10),
                                  controller.speakState.value
                                      ? Expanded(
                                          child: SoundsMessageButton(
                                            onChanged: (status) {
                                              debugPrint(
                                                status.toString(),
                                              );
                                            },
                                            onSendSounds:
                                                (valuel1, valuel2, time) {
                                              if (valuel1 ==
                                                  SendContentType.voice) {
                                                DDLogService().ddGa(page: "commen_send_sound");
                                                controller.sendSound(
                                                    model, valuel2, time);
                                              }
                                            },
                                          ),
                                        )
                                      : Expanded(
                                          child: Container(
                                            height: 36,
                                            decoration: BoxDecoration(
                                              color: Colors.grey[200],
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              border: Border.all(
                                                color: Color(0xFF4C5961),
                                                width: 1,
                                              ),
                                            ),
                                            child: TextField(
                                              controller: controller.control,
                                              textAlign: TextAlign.start,
                                              focusNode: controller.focusNode,
                                              maxLength: 40,
                                              showCursor: false,
                                              keyboardType: TextInputType.text,
                                              style: TextStyle(fontSize: 12),
                                              decoration: const InputDecoration(
                                                hintText: "Say something.",
                                                hintStyle: TextStyle(
                                                    color: Colors.grey,
                                                    fontSize: 12),
                                                counterText: '',
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.only(
                                                    left: 10,
                                                    right: 10,
                                                    bottom: 15),
                                              ),
                                            ),
                                          ),
                                        ),
                                  SizedBox(width: 10),
                                  IconButton(
                                      onPressed: () {
                                        if (!controller.speakState.value) {
                                          DDLogService().ddGa(page: "commen_send_message");
                                          controller.sendMessage(model);
                                        }
                                      },
                                      icon: controller.speakState.value
                                          ? Image.asset(R.assetsImagesHome8)
                                          : Image.asset(R.assetsImagesHome8)),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }
}

class CommentItem extends StatefulWidget {
  final HiveCommentModel model;
  final Function()? onClick;
  const CommentItem({Key? key, required this.model, this.onClick})
      : super(key: key);

  @override
  State<CommentItem> createState() => _CommentItemState();
}

class _CommentItemState extends State<CommentItem> {
  final AudioPlayer audioPlayer = AudioPlayer();

  bool _isPlaying = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Future<void> dispose() async {
    audioPlayer.dispose();
    super.dispose();
  }

  Future<void> play() async {
    if (_isPlaying) {
      await audioPlayer.stop();
    } else {
      await audioPlayer.play(DeviceFileSource(widget.model.message ?? ''));
    }
    _isPlaying = !_isPlaying;
  }

  Future<void> pause() async {
    await audioPlayer.pause();
  }

  Future<void> stop() async {
    await audioPlayer.stop();
  }

  @override
  Widget build(BuildContext context) {
    return DDViewBackGround(
      margin: EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10),
      borderWidth: 3,
      boxShadowOffset: Offset(3, 3),
      content: Padding(
        padding: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(16.0),
                  child: CachedNetworkImage(
                    width: 32,
                    height: 32,
                    imageUrl: widget.model.iconUrl ?? '',
                    placeholder: (context, url) => Placeholder(),
                    errorWidget: (context, url, error) => Placeholder(),
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: Text(
                    widget.model.name ?? '',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                        color: Color(0xFF202020)),
                  ),
                ),
                SizedBox(width: 10),
                IconButton(
                  onPressed: () {
                    if (widget.onClick != null) {
                      widget.onClick!();
                    }
                  },
                  icon: Image.asset((widget.model.myLikes ?? false)
                      ? R.assetsImagesHomeSecond6
                      : R.assetsImagesHomeSecond4),
                )
              ],
            ),
            SizedBox(height: 5),
            widget.model.type == 2
                ? Padding(
                    padding:
                        EdgeInsets.only(left: 40, right: 0, top: 0, bottom: 10),
                    child: DDSafeButton(
                      onPressed: () {
                        play();
                      },
                      child: Container(
                        width: 80,
                        height: 28,
                        decoration: BoxDecoration(
                          color: Color(0xff53BFD7),
                          borderRadius: BorderRadius.all(Radius.circular(8)),
                        ),
                        child: Center(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(R.assetsImagesHome16),
                              SizedBox(width: 5),
                              Text(
                                "${widget.model.soundTime}s",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ))
                : Container(
                    padding: EdgeInsets.only(
                        left: 10, right: 10, top: 10, bottom: 10),
                    child: Text(
                      widget.model.message ?? '',
                      textAlign: TextAlign.left,
                      style: TextStyle(fontSize: 12, color: Color(0x80000000)),
                    ),
                  ),
          ],
        ),
      ),
    );
  }
}
